package com.platform.qujia.service.impl;

import com.platform.qujia.dao.CommodityMapper;
import com.platform.qujia.dao.NonOilOrderMapper;
import com.platform.qujia.dao.OrderDetailsMapper;
import com.platform.qujia.pojo.nonOil.Commodity;
import com.platform.qujia.pojo.nonOil.NonOilOrder;
import com.platform.qujia.pojo.nonOil.OrderDetails;
import com.platform.qujia.service.DualNonOilOrderCreateService;
import com.platform.qujia.utils.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service("dualNonOilOrderCreateService")
@Slf4j
public class DualNonOilOrderCreateServiceImpl implements DualNonOilOrderCreateService {

    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private OrderDetailsMapper orderDetailsMapper;

    @Autowired
    private NonOilOrderMapper nonOilOrderMapper;

    @Override
    @Transactional
    public void orderCallback(String orderNo){
        NonOilOrder nonOilOrder = nonOilOrderMapper.selectByOrderCode(orderNo);
        if(Objects.isNull(nonOilOrder)){
//            callBackCommodity(orderNo);
            throw new CustomException("回调验签失败 订单号不存在");
        }
        NonOilOrder newNonOilOrder = new NonOilOrder();
        newNonOilOrder.setOrderCode(nonOilOrder.getOrderCode());
        newNonOilOrder.setStatus("1");
        newNonOilOrder.setPayTime(new Date());
        nonOilOrderMapper.updateByOrderCode(newNonOilOrder);

        // 便利店特性 支付成功后才扣减库存
        List<OrderDetails> orderDetails = orderDetailsMapper.selectByOrderCode(orderNo);
        for (OrderDetails orderDetail : orderDetails) {
            Commodity commodity = commodityMapper.selectByPrimaryKey(orderDetail.getCommodityId());
            Commodity com = new Commodity();
            com.setCommodityId(commodity.getCommodityId());
            com.setInventory(commodity.getInventory() - orderDetail.getCommodityNum());
            commodityMapper.updateByPrimaryKeySelective(com);
        }
    }
}
